package com.bw.kotlindemo.java.activity;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Observer;

import com.bw.kotlindemo.R;
import com.bw.kotlindemo.databinding.ActivityLiveListBinding;
import com.bw.kotlindemo.java.base.BaseActivity;
import com.bw.kotlindemo.java.fragment.LiveListFragment;
import com.bw.kotlindemo.java.model.bean.TypeBean;
import com.bw.kotlindemo.java.utils.ToastUtil;
import com.bw.kotlindemo.java.vm.LiveVM;

import java.util.ArrayList;
import java.util.List;

/**
 * desc:直播列表类
 * create by xushaodong on 2023/3/22
 */
public class LiveListActivity extends BaseActivity<LiveVM, ActivityLiveListBinding> {
    List<Fragment> list = new ArrayList<Fragment>();
    private TypeBean mTypeBean;

    @Override
    protected int initLayout() {
        return R.layout.activity_live_list;
    }

    @Override
    protected void initCoding() {
        initLiveData();
        loadData();
    }

    /**
     * 请求网路
     */
    private void loadData() {
        mViewModel.getTypeList();
    }

    /**
     * 配置liveData回调
     */
    private void initLiveData(){
        mViewModel.liveTypeData.observe(this, new Observer<TypeBean>(){
            @Override
            public void onChanged(TypeBean typeBean) {
                if(typeBean.getStatus().equals("0000")) {
                    mTypeBean = typeBean;
                    initView();// 网络请求到数据后，再去初始化view，因为刚打开页面，还没有tab数据
                } else {
                    ToastUtil.showToast(typeBean.getMessage());
                }
            }
        });

        mViewModel.errorVM.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtil.showToast(s);
            }
        });
    }

    protected void initView() {
        for(TypeBean.ResultBean resultBean : mTypeBean.getResult()){
            list.add(new LiveListFragment(resultBean));
        }


        mDataBinding.viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
//                if(position == 0){
//                    return (Fragment) ARouter.getInstance().build("/fragments/one").navigation();
//                }
                return list.get(position);
            }

            @Override
            public int getCount() {
                return list.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTypeBean.getResult().get(position).getName();
            }
        });
        mDataBinding.tabLayout.setupWithViewPager(mDataBinding.viewPager);
    }


}
